import {Component} from "vue"
import { createRouter, createWebHistory, RouteRecordRaw,RouteMeta } from "vue-router";
import page404 from "@/views/error/404.vue";
import page401 from "@/views/error/401.vue";
import LayoutBase from "@/layout/base/index.vue";
import LayoutEmpty from "@/layout/empty/index.vue";
import { treeMap } from "../utils/tree";
const PAGES = import.meta.glob("@/views/**/*.vue");
const PATHS = Object.keys(PAGES);
const NAMES = PATHS.map((k) => k.replace(/.*?views\//, ""));
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/base",
    name: "BASE_ROUTER",
    component:LayoutBase,
  },
  {
    path: "/404",
    name: "404",
    component: page404,
  },
  {
    path: "/401",
    name: "401",
    component: page401,
  },
  {
    path: "/*",
    redirect: "/404",
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
  // 修复路由切换滚动条没有重置 bug
  scrollBehavior() { 
    // 始终滚动到顶部
    return { top: 0 };
  },
});

// 路由守护
router.beforeEach((to, from, next) => {
  if (to.path === from.path) {
    return;
  }
  next();
});

export default router;

export interface RouteData {
  name: string;
  path: string;
  redirect?: string;
  component?: string;
  meta?: string;
  children?: RouteData[];
}
// 动态路由
export const addRoutes = (routes: RouteData[]) => {
  treeMap(routes, (n, l, ins, p) => {
    const { name, path, redirect = '', meta:m } = n;
    if(!router.hasRoute(name)){
      return ;
    }
    const c = n.component ?? path ?? "";
    const i = NAMES.indexOf(c);
    const component:Component = i != -1 ? PAGES[PATHS[i]] : LayoutEmpty;
    let meta:RouteMeta = {};
    try {
      if(m){
        meta = JSON.parse(m)
      }
    } catch (error) {
      console.error('==== 路由 meta 解析失败！=====',m)
    }
    const data = { name, path, redirect, meta, component } as RouteRecordRaw;
    const pName = p?.name || "BASE_ROUTER";
    router.addRoute(pName,data)
  });
};
